package calao.contact;

import calao.contact.client.Contact;
import calao.contact.client.Organization;
import calao.contact.client.Person;
import calao.storage.Record;
import calao.storage.RecordBinding;

import static calao.contact.ContactDB.*;

public class ContactBinding 
extends RecordBinding<Contact>
{
	
	ContactBinding()
	{
		super(Contact.class);
	}

	public Contact toObject(Record record)
	{
		int id = record.getInt(ID);
		boolean isPerson = record.get(TYPE)==PERSON;
		Person person = isPerson? new Person(id) : null;
		Organization org = isPerson? null : new Organization(id);
		Contact info = isPerson? person : org;
		info.setName(record.get(NAME));
		info.setPhone(record.get(PHONE));
		info.setFax(record.get(FAX));
		info.setEmail(record.get(EMAIL));
		info.setGroups(record.getAllInt(GROUP));
		info.setAddress(record.get(POST_ADDRESS));
		info.setNotes(record.get(NOTES));
		if (isPerson) {
			person.setOrganization(record.getInt(PERSON_ORGANIZATION));
			person.setFirstName(record.get(FIRST_NAME));
		}
		else {
			org.setCompanyNumber(record.get(ORGANIZATION_COMPANY_NUMBER));
			org.setVATNumber(record.get(ORGANIZATION_VAT_NUMBER));
			org.setVATRate(record.getDouble(ORGANIZATION_VAT_RATE));
		}
		return info;
	}

	public Record toRecord(Contact info) 
	{
		Record rec = new Record(TABLE);
		rec.set(ID, info.getId());
		rec.set(NAME, info.getName());
		rec.set(PHONE, info.getPhone());
		rec.set(FAX, info.getFax());
		rec.set(EMAIL, info.getEmail());
		rec.set(GROUP, info.getGroups());
		rec.set(POST_ADDRESS, info.getAddress());
		rec.set(NOTES, info.getNotes());
		if (info instanceof Person) {
			Person person = (Person)info;
			rec.set(TYPE, PERSON);
			rec.set(FIRST_NAME, person.getFirstName());
			rec.set(PERSON_ORGANIZATION, person.getOrganization());
		}
		else {
			Organization org = (Organization)info;
			rec.set(TYPE, ORGANIZATION);
			rec.set(ORGANIZATION_VAT_NUMBER, org.getVATNumber());
			rec.set(ORGANIZATION_VAT_RATE, org.getVATRate());
			rec.set(ORGANIZATION_COMPANY_NUMBER, org.getCompanyNumber());
		}
		return rec;
	}

}
